package com.jwpdk.appframework.data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@SuppressWarnings("unchecked")
public class DatasetList extends ArrayList implements IDataList {

	private static final long	serialVersionUID	= -3862651429961234865L;

	/**
	 * construct function
	 */
	public DatasetList() {
		super();
	}

	/**
	 * construct function
	 * @param list
	 */

	public DatasetList(List list) {
		addAll(list);
	}

	/**
	 * get object
	 * @param index
	 * @param name
	 * @return Object
	 */
	public Object get(int index, String name) {
		IData data = (IData) get(index);
		return data == null ? null : data.get(name);
	}

	/**
	 * get object
	 * @param index
	 * @param name
	 * @param def
	 * @return Object
	 */
	public Object get(int index, String name, Object def) {
		Object value = get(index,name);
		return value == null ? def : value;
	}

	/**
	 * to data
	 * @return IData
	 */

	public IData toData() throws Exception {
		IData data = new DataMap();

		Iterator it = iterator();
		while ( it.hasNext() ) {
			IData element = (IData) it.next();
			Iterator iterator = element.keySet().iterator();
			while ( iterator.hasNext() ) {
				String key = (String) iterator.next();
				if ( data.containsKey(key) ) {
					List list = (List) data.get(key);
					list.add(element.get(key));
				} else {
					List list = new ArrayList();
					list.add(element.get(key));
					data.put(key,list);
				}
			}
		}

		return data;
	}

	/**
	 * get count
	 * @return int
	 */
	public int count() {
		return size();
	}

	/**
	 * key 排序字段 keyType 字段数据类型
	 */
	public void sort(String key, int keyType) {
		sort(key,keyType,IDataList.ORDER_ASCEND);
	}

	/**
	 * key 排序字段 keyType 字段数据类型 order 升降序
	 */
	public void sort(String key, int keyType, int order) {
		Object[] datas = (Object[]) this.toArray();
		DataComparator c = new DataComparator(key, keyType, order);
		Arrays.sort(datas,c);
		List list = Arrays.asList(datas);
		this.clear();
		this.addAll(list);
	}

	/**
	 * sort double (default ascend)
	 */
	public void sort(String key1, int keyType1, String key2, int keyType2) {
		sort(key1,keyType1,IDataList.ORDER_ASCEND);
		sort(key2,keyType2,IDataList.ORDER_ASCEND,key1,keyType1);
	}

	/**
	 * sort double
	 */
	public void sort(String key1, int keyType1, int order1, String key2, int keyType2, int order2) {
		sort(key1,keyType1,order1);
		sort(key2,keyType2,order2,key1,keyType1);
	}

	/**
	 * sort assistant
	 */
	private void sort(String key, int type, int order, String fix, int fixType) {
		Object[] datas = (Object[]) this.toArray();

		DataComparator c = new DataComparator(key, type, order);

		if ( fix == null ) {
			Arrays.sort(datas,c);
		} else {
			int[] marks = Anchor.mark(this,fix,fixType);

			for (int pre = 0, i = 1; i < marks.length; i++) {
				Arrays.sort(datas,pre,marks[i],c);
				pre = marks[i];
			}
		}
		List list = Arrays.asList(datas);

		this.clear();
		this.addAll(list);
	}
}